package com.ichengzi.audit.human.repository.mysql.controller;

import com.ichengzi.audit.human.repository.mysql.constant.Constant;
import com.ichengzi.audit.human.repository.mysql.service.CodeGeneratorService;
import com.ichengzi.audit.human.repository.mysql.utils.FileUtil;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author lihn
 */
@Api(tags = {"mybatis-plus 代码生成"})
@RestController
@RequestMapping("/code")
public class CodeGeneratorController {
    @Resource(name = "codeGeneratorService")
    private CodeGeneratorService codeGeneratorService;

    /**
     * 生成 mybatis 文件
     * @param tableNames 表名，多个以逗号隔开
     * @param response HttpServletResponse
     */
    @PostMapping("/generator")
    @ApiOperation(value = "根据表名生成 mybatis 文件")
    @ApiImplicitParam(name = "tableNames", value = "表名，多个以逗号隔开", dataType = "String", required = true)
    public void generator(String tableNames, HttpServletResponse response) {
        if(StringUtils.isNullOrEmpty(tableNames)){
            throw new RuntimeException("表名为空，无法生成相关代码！");
        }
        String path = codeGeneratorService.generator(tableNames);
        if(!path.endsWith(Constant.CODE_ZIP_NAME)){
            throw new RuntimeException("代码生成失败！");
        }
        try {
            // path是指想要下载的文件的路径
            File file = new File(path);
            // 获取文件名
            String filename = file.getName();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", String.valueOf(file.length()));
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            path = path.substring(0,path.lastIndexOf(File.separator));
            FileUtil.deleteDirectory(path);
        }
    }

}
